package cmd

import (
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/cobra/doc"
)

// gendocCmd represents the gendoc command
var gendocCmd = &cobra.Command{
	Use:    "gendoc <output-dir>",
	Short:  "Generate CLI documentation in markdown format",
	Args:   cobra.ExactArgs(1),
	Hidden: true,
	Run:    runGendoc,
}

func init() {
	rootCmd.AddCommand(gendocCmd)
}

func runGendoc(cmd *cobra.Command, args []string) {
	outputDir := args[0]

	// Ensure the output directory exists
	if err := os.MkdirAll(outputDir, 0o755); err != nil {
		log.FATAL.Fatalf("Failed to create output directory: %v", err)
	}

	if err := doc.GenMarkdownTree(rootCmd, outputDir); err != nil {
		log.FATAL.Fatalf("Failed to generate documentation: %v", err)
	}

	// make some modifications to the generated files
	err := filepath.Walk(outputDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() && strings.HasSuffix(info.Name(), ".md") {
			content, err := os.ReadFile(path)
			if err != nil {
				return err
			}

			// reduce header level by one
			modifiedContent := strings.ReplaceAll(string(content), "## ", "# ")
			// lowercase "see also"
			modifiedContent = strings.ReplaceAll(modifiedContent, "SEE ALSO", "See also")
			// convert single line indented code to backtick surrounded code
			codeRe := regexp.MustCompile("\n\n\t(.*)\n")
			modifiedContent = codeRe.ReplaceAllString(modifiedContent, "\n\n```\n$1\n```\n")
			// remove auto generated date line
			dateRe := regexp.MustCompile("##### Auto generated by spf13/cobra on.*\n")
			modifiedContent = dateRe.ReplaceAllString(modifiedContent, "\n")

			if err := os.WriteFile(path, []byte(modifiedContent), 0o644); err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		log.FATAL.Fatalf("Failed to modify documentation: %v", err)
	}

	log.INFO.Printf("Documentation generated and modified in %s", outputDir)
}
